package io.chenhd.gateway.filter;

import io.chenhd.gateway.cache.ContextCache;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AttributeKey;

import java.util.UUID;

/**
 * Create by chenhd on 2021/8/21.
 */
public class RequestLogFilter extends ChannelInboundHandlerAdapter implements HttpRequestFilter {
    @Override
    public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
        AttributeKey<String> requestKey = AttributeKey.valueOf("requestId");
        String requestId = UUID.randomUUID().toString().replaceAll("-", "");
        //引入log后可将requestId作为MDC
        ctx.channel().attr(requestKey).set(requestId);
        ContextCache.contextTimeCache.put(requestId, System.currentTimeMillis());
        System.out.println(String.format("requestId %s request: uri:%s, method:%s", requestId, fullRequest.uri(), fullRequest.method()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fullRequest = (FullHttpRequest) msg;
        filter(fullRequest, ctx);
        ctx.fireChannelRead(msg);
    }
}
